<?php

class User extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->library('layout', array('main')); //加载layouts下的main文件，可以写其他的布局文件，如$this->load->library('layout',array('hello'));表示加载layouts下的hello布局文件，默认$this->load->library('layout')不传参表示加载默认的布局文件，在layout扩展类的构造方法中已经设置了默认参数main
        $this->load->model('Users_model','users');
    }

    public function index()
    {

        if ($this->valiedUserLogin()) {
            redirect('login/index');
        }
       
        $users = $this->users->get_user_list();


        $this->layout->view('user/index', ['users'=>$users]);
    }
    public function create()
    {

        $this->layout->view('user/create');
    }
    /**
     *  保存数据
     *  表单验证
     */
    public function store()
    {

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required',
            array('required' => 'You must provide a %s.')
        );
        $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required');

        if ($this->form_validation->run() == false) {
            $this->layout->view('user/create');
        } else {
            if ($_POST) {
                $username = $this->input->post('username');
                $email = $this->input->post('email');
                $password = $this->input->post('password');
                $mobile = $this->input->post('mobile');

                $data = ['username' => $username, 'email' => $email, 'password' => $password, 'mobile' => $mobile];
                if ($this->db->insert('users', $data)) {
                    redirect('user/index');
                } else {
                    redirect('user/create');
                }
            }

        }

    }
    /**
     *  编辑
     */
    public function edit($id)
    {

   

        if ($_POST) {

            $data1 = ['username' => $this->input->post('username'),
                'email' => $this->input->post('email'),
                'mobile' => $this->input->post('mobile'),
            ];

            $this->db->where('id', $id);
            $rs = $this->db->update('users', $data1);
            if ($rs) {
                redirect('user/index');
            }
            $this->layout->view('user/edit', $data);
            exit;
        }
        $user = $this->users->find_user($id);
        
        $this->layout->view('user/edit', ['user'=>$user]);
    }
    /**
     *  退出系统
     */
    public function logout()
    {
        $this->session->unset_userdata('user', '');
        redirect('login/index');
    }
}
